package com.pavelkaminsky;

import com.mongodb.*;
import com.restfb.types.User;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.List;


/**
 * @Author: Pavel Kaminsky
 * @Site : www.pavel-kaminsky.com
 * @Date: 08/10/11
 */

public class MongoDB {

    private DB friendsDB;

    public MongoDB() {
        try {

            String dbHost = ApplicationProperties.getInstance().getProperty("DB.HOST");
            String dbPort = ApplicationProperties.getInstance().getProperty("DB.PORT");

            Mongo mongoDB = new Mongo(dbHost, Integer.valueOf(dbPort));
            friendsDB = mongoDB.getDB("friendsDB");

        } catch (UnknownHostException e) {
            System.out.println(e);
        }
    }

    public void storeFriends(List<User> friends) {
        DBCollection coll = friendsDB.getCollection("friendsCollection");
        SimpleDateFormat simpleDateformat = new SimpleDateFormat("yyyy");


        for (User friend : friends) {
            BasicDBObject doc = new BasicDBObject();

            doc.put("fid", friend.getId());
            doc.put("name", friend.getName());

            if(friend.getBirthdayAsDate() != null)
                doc.put("yearOfBirth", simpleDateformat.format(friend.getBirthdayAsDate()));

            if(friend.getHometownName() != null)
                doc.put("hometown", friend.getHometownName());

            coll.insert(doc);
        }
    }

    public List<DBObject> findFriendsByYear(String year) {

        BasicDBObject query = new BasicDBObject();
        query.put("yearOfBirth", year);
        DBCursor cur = friendsDB.getCollection("friendsCollection").find(query);
        return cur.toArray();
    }

    public List<DBObject> findTelAvivFriends() {

        BasicDBObject query = new BasicDBObject();
        query.put("hometown", "Tel Aviv");
        DBCursor cur = friendsDB.getCollection("friendsCollection").find(query);
        return cur.toArray();
    }
}
